package org.zoomdev.zoom.protobuf.modules;

import io.protostuff.ByteArrayInput;
import io.protostuff.ProtostuffOutput;

import java.io.IOException;
import java.lang.reflect.Array;

public final class ArraySchema implements ISchema {
    private final ISchema schema;
    private final Class type;

    public ArraySchema( Class type) {
        this.schema = ISchemaFactory.createFromClass(type);
        this.type = type;
    }

    @Override
    public void write(ProtostuffOutput output, int index, Object value, boolean repeat) throws IOException {
        int len = Array.getLength(value);
        output.writeInt32(index, len, true);
        for (int i = 0; i < len; ++i) {
            Object data = Array.get(value, i);
            if (data == null) {
                throw new NullPointerException("pojo数据不能为空");
            }
            schema.write(output, index + i, data, true);
        }
    }

    @Override
    public Object mergeFrom(ByteArrayInput input) throws IOException {
        int len = input.readInt32();
        Object obj = Array.newInstance(type, len);
        for (int i = 0; i < len; ++i) {
            input.readFieldNumber(null);
            Object value = schema.mergeFrom(input);
            Array.set(obj, i, value);
        }
        return obj;
    }
}
